package com.lasun.server;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import com.jfinal.kit.JsonKit;
import com.lasun.server.entity.Client;
import com.lasun.server.entity.World;

public class TcpServerHandler extends ChannelInboundHandlerAdapter {
	// private static final Logger logger =
	// Logger.getLogger(TcpServerHandler.class);
	private final static PacketHandler packetHandler = new PacketHandler();
	private final World world = World.getWorld();
	private static ArrayList<String[]> clientMsgList = new ArrayList<String[]>();
	private MessageServer iMessagServer;

	public TcpServerHandler(MessageServer iMessagServe) {
		// TODO Auto-generated constructor stub
		this.iMessagServer = iMessagServe;
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		// logger.info("SERVER接收到消息:"+msg);
		System.out.println("SERVER接收到消息:" + msg);
		if (((String) msg).contains("@C")) {
			String msgStr[] = chaiFen((String) msg);
			clientMsgList.add(msgStr);
			iMessagServer.datacallback(clientMsgList, packetHandler);
			HashMap<String, String>hashMap=(HashMap<String, String>) connectServer(String2Map(msgStr), chaiFen2(msgStr[0])[1]);
			if(hashMap!=null){
				//String str = map2String(hashMap, chaiFen2(msgStr[0])[1], chaiFen2(msgStr[6])[1]);
//				String str = JsonKit.mapToJson(hashMap, hashMap.size());
				String str = "";
				packetHandler.handle(str);
			}
		} else {
			packetHandler.handle(msg);
		}
	}

	private HashMap<String, String> connectServer(Map<String, Object> map,
			String appcode) {
		Map mapClient = map;
		String appCode = appcode;
		try {

			Object[] objs = new Object[2];
			objs[0] = appCode;
			objs[1] = mapClient;

			Class[] clsTypes = new Class[2];
			clsTypes[0] = String.class;
			clsTypes[1] = Map.class;

			Class cls = Class.forName("app.server.s02.AppServerManage");
			Method method = cls.getDeclaredMethod("connectServer", clsTypes);
			return (HashMap<String, String>) method.invoke(cls.newInstance(), objs);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}

	}

	private String map2String(Map<String, String> map,String appid,String phoneid) {
		StringBuilder str = new StringBuilder();
		str.append("appcode"+":/"+appid+"@C"+"vcode"+":/"+phoneid+"@C");
		for (Iterator<String> it = map.keySet().iterator(); it.hasNext();) {
			String key = (String) it.next();
			String c = String.valueOf(map.get(key));
			if (it.hasNext()) {
				str.append(key + ":/" + c + "@C");
			}
			else{str.append(key + ":/" + c);}
		}
		return str.toString();

	}

	// public static void sendMessage(String msg){
	// packetHandler.handle(msg);
	// }

	//
	// /**
	// *
	// * @return 字符串数组的集合 内包含 客户端传来的用户参数
	// */
	// public static ArrayList<String[]> getClientMsgList() {
	// System.out.println(clientMsgList.size());
	//
	// return clientMsgList;
	// }

	@Override
	public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
		world.register(new Client(ctx.channel()));
	}

	@Override
	public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
		world.unregister(ctx.channel().hashCode());
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		// logger.warn("Unexpected exception from downstream.", cause);
		System.out.println("服务端异常：" + cause);
		// cause.printStackTrace();
		world.unregister(ctx.channel().hashCode());
		ctx.close();
	}

	/***
	 * 
	 * @param 客户端传来的msg
	 * @return 拆分成字符串数组的msg
	 */
	public String[] chaiFen(String s) {
		String[] str = null;
		if (!s.contains("@C")) {
			str = new String[] { s };
		} else {
			str = s.split("@C");
		}
		return str;
	}

	public String[] chaiFen2(String s) {
		String[] str = null;
		if (!s.contains(":/")) {
			str = new String[] { s };
		} else {
			str = s.split(":/");
		}
		return str;
	}

	/***
	 * 
	 * @param chaifen的返回值
	 * @return 数据的map集合
	 */
	public Map<String, Object> String2Map(String[] str) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		for (int i = 0; i < str.length; i++) {
			try {
				map.put(chaiFen2(str[i])[0], chaiFen2(str[i])[1]);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				System.out.print(str[i]+"数据错误");
			}
		}
		return map;

	}

}